import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, Spin, Button,
    message, Card, Row,
    Col, Radio, Form,
    Input, DatePicker, Select,
    Table, Upload, Icon,
    Popconfirm, Progress } from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import { FormattedMessage } from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import moment from "moment";
import router from 'umi/router';

const { Dragger } = Upload;

let checkUserInterval = null;

@connect(({ journalModel }) => ({
    journalModel
}))
@Form.create()
class editJournal extends Component {

    state = {
        loading: false,
        editDataId: null,
        editData: {},
        gvList: [],
        customerList: null,
        pointList: null,
        joPointList: [],
        isShowCustomerModal: false,
        selectedFile: null,
        isShowPointModal: false,
        pointSelectedKeys: [],
        fromList: null,
        isShowAddPointModal: false,
        addAfter:false,
        journalMaxLimit:null,
        progressShow:false,
        percent:0
    };

    componentDidMount() {
        this.initPageParams();
        this.findGvDataSource();
        this.getJournalMaxLimit();
    }

    initPageParams() {
        const { state } = this.props.location;
        if (APP.isValidObj(state)) {
            const { id,fromList } = state;
            const that = this;
            if (id) {
                const state = {editDataId: id};
                if (fromList) {
                    state.fromList = fromList;
                }

                this.setState(state, function(){
                    that.findJoPoint(false);
                });
                this.getDataById(id);
            } else if (fromList) {
                this.setState({fromList:fromList});
            }
        }
    }

    getDataById = (id) => {
        if(!id || !APP.isValidObj(id)) return;
        const that = this;
        const { dispatch, form } = that.props;
        APP.loading(that);
        dispatch({
            type: "journalModel/getJournalById",
            payload: {id: id},
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    form.resetFields();
                    that.setState({
                        editData: data.datas
                    });
                }
            }
        });
    };

    findGvDataSource = () => {
        const that = this;
        const { dispatch } = that.props;
        dispatch({
            type: "commonModel/gvList",
            payload: {code: "500001"},
            callback: function(data){
                if(data.success){
                    that.setState({gvList: data.datas});
                }
            }
        });
    };

    findCustomerList = (e, form) => {
        const that = this;
        const { dispatch } = that.props;
        let params = {};
        if(e) e.preventDefault();
        if(form){
            form.validateFieldsAndScroll((err, values) => {
                APP.validNilParams(values);
                params = {...params, ...values};
                requestContinue();
            });
        }else requestContinue();
        function requestContinue(){
            APP.loading(that);
            dispatch({
                type: "journalModel/customerList",
                payload: params,
                callback: function(data){
                    APP.closeLoading(that);
                    if(data.success){
                        that.setState({
                            customerList: data.datas,
                            isShowCustomerModal: true
                        });
                    }
                }
            });
        }
    };

    submit = (e) => {
        e.preventDefault();
        const that = this;
        const { dispatch, form } = that.props;
        const { selectedFile,fromList } = this.state;
        form.validateFieldsAndScroll((err, values) => {
            if(err) return;
            APP.validNilParams(values);
            values.expireDate = APP.momentFormatToStr(values.expireDate);
            if (values.atype === 3) {
                values.fileSize = 0;
                values.fileMd5 = '';
                if (values.filePath.length > 300) {
                    Modal.error({content:'文本素材长度不能超过300字符。'});
                    return;
                }
            }
            APP.loading(that);
            if(selectedFile){
                values.filePath = selectedFile.filePath;
                values.fileSize = selectedFile.fileSize;
                values.attachmentId = selectedFile.attachmentId;
                values.fileMd5 = selectedFile.fileMd5;
                values.newFile = true;
                values.isServerPath = selectedFile.isServerPath;
                requestContinue(values);
                // that.fileUpload(selectedFile.originFileObj, 10001, function(data){
                //     values.filePath = data.datas.filePath;
                //     values.fileSize = data.datas.fileSize;
                //     requestContinue(values);
                // });
            }else {
                values.newFile = false;
                requestContinue(values);
            }
        });

        function requestContinue(params){
            APP.loading(that);
            dispatch({
                type: "journalModel/saveJournal",
                payload: params,
                callback: function(data){
                    if(data.success){
                        APP.closeLoading(that);
                        if(params.id){
                            message.success("提交成功");
                            that.callbackToList();
                        }else{
                            message.success("提交成功，开始添加点位吧~");
                            that.props.location.state = {
                                id: data.datas.id,
                                fromList: fromList
                            };
                            that.setState({
                                isShowAddPointModal:true,
                                addAfter:true
                            });
                            that.initPageParams();
                        }
                    }else{
                        APP.closeLoading(that);
                        message.error(data.msg);
                    }
                }
            });
        }
    };

    callbackToList() {
        router.push({
            pathname: '/journal/journal',
            state: {}
        });
    }

    //-- 显示/隐藏 添加点位窗口
    handlerAddPointModal(){
        const that = this;
        let { isShowAddPointModal } = this.state;
        isShowAddPointModal = !isShowAddPointModal;
        this.setState({ isShowAddPointModal });
        if (isShowAddPointModal) {
            that.findJoPoint(true);
        }
    }

    fileUpload = (file, formType, callback, failCallback) => {
        const thisCtx = this;
        const { dispatch } = this.props;
        const formData = new window.FormData();
        formData.append('file', file);
        formData.append('formType', formType);
        dispatch({
            type: "commonModel/fileUploadOfText",
            payload: formData,
            callback: function(data) {
                if (!data.success) {
                    APP.errorMessage(thisCtx, "文件上传失败");
                    failCallback();
                } else {
                    if (APP.isValidObj(callback)) {
                        callback(data);
                    }else APP.closeLoading();
                }
            },
        });
    };

    findJoPoint = (loading = true) => {
        const { dispatch } = this.props;
        const { editDataId } = this.state;
        const that = this;
        if(loading) APP.loading(that);
        dispatch({
            type: "journalModel/getJoPoint",
            payload: {journalId: editDataId},
            callback: function(data){
                if(loading) APP.closeLoading(that);
                if(data.success){
                    that.setState({joPointList: data.datas});
                }
            }
        });
    };

    render() {
        const that = this;
        const {
            loading,
            editData,
            gvList,
            selectedFile,
            fromList,
            addAfter,
            journalMaxLimit
        } = that.state;
        const { form } = that.props;
        const { getFieldDecorator } = form;
        const formItemLayout = {
            style: {
                margin: '10px',
            },
        };
        const gvOptions = gvList.map((item) => {
            return <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>;
        });
        const formDatums = this.props.form.getFieldsValue();
        const isVideo = 1 == formDatums.atype;
        const isImage = 2 == formDatums.atype;
        const isFile = isVideo || isImage;

        function fileComponentProgress(info) {
            const event = info.event;
            let isOut = true;
            if (event) {
                const percent = Math.floor((event.loaded / event.total) * 100);
                let progressShow = percent < 100;
                that.setState({
                    percent:percent,
                    progressShow:progressShow
                });
            } else {
                const status = info.file.status;
                if (status === 'error') {
                    that.setState({progressShow:false},function () {
                        Modal.error({
                            content:'上传出错'
                        });
                    });
                } else if (status === 'done') {
                    isOut = false;
                }
            }
            return isOut;
        }

        function fileDispatchProgress() {
            that.setState({
                progressShow:true,
                percent:0
            },function () {
                let percent = 1;
                function whileDispatch() {
                    that.setState({percent:percent});
                    if (percent >= 100) {
                        that.setState({progressShow:false},function () {
                            clearInterval(checkUserInterval);
                        });
                    } else {
                        percent++;
                    }
                }
                if (checkUserInterval == null) {
                    const timeout = 1000;
                    checkUserInterval = setInterval(whileDispatch, timeout);
                }
            });
        }

        const uploadHandler = {
            action: '../api/v1/attachment/upload',
            accept: isVideo ? ".mp4" : ".jpeg,.jpg,.png",
            showUploadList: false,
            data:file => {
                return {
                    formType:10001,
                    toServer:true
                };
            },
            //-- 上传前检测文件
            beforeUpload: function(file) {
                //-- 文件大小检测
                const fileSize = file.size / 1024 / 1024;
                if (APP.isValidObj(journalMaxLimit)) {
                    const checkFileSize = fileSize < parseFloat(journalMaxLimit);
                    if (!checkFileSize) {
                        message.error('文件必须小于' + journalMaxLimit + 'MB!');
                        return false;
                    }
                }
                if(isVideo && ["video/mp4"].indexOf(file.type) === -1){
                    message.error('文件格式不正确!');
                    return false;
                }
                that.state.percent = 0;
                return true;
            },
            onChange: function(info) {
                if(fileComponentProgress(info)) return;
                if(isVideo && ["video/mp4"].indexOf(info.file.type) === -1) return;
                if(info.file.originFileObj === undefined) return;
                APP.getImageFileBase64(info.file.originFileObj, image => {
                    const selectedFile = info.file;
                    info.file.base64 = image;
                    const response = selectedFile.response;
                    if (response.success) {
                        that.setState({
                            selectedFile:{
                                filePath:response.datas.filePath,
                                fileSize:response.datas.fileSize,
                                attachmentId:response.datas.attachmentId,
                                fileMd5:response.datas.fileMd5,
                                isServerPath:response.datas.isServerPath,
                            }
                        });
                    } else {
                        Modal.error({content:response.msg});
                    }
                });
            }
        };
        function disabledDate(current) {
            // Can not select days before today and today
            return current && current < moment().subtract(1, 'days');
        }
        let callbackToListBtn = '';
        if (fromList) {
            callbackToListBtn = <Button type={'primary'} {...APP.buttonsStyle_MR15} onClick={() => {that.callbackToList()}}>返回期刊列表</Button>;
        }
        let readOnly = false;
        let allowClear = true;
        if (fromList === 'look') {
            readOnly = true;
            allowClear = false;
        }
        let submitBtn = <Button type="primary" {...APP.buttonsStyle_MR15} htmlType="submit" hidden={readOnly}>提交</Button>;
        if (addAfter) {
            submitBtn = <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {that.handlerAddPointModal()}}>添加点位</Button>;
        }

        function getLocalFile(filePath) {
            return encodeURI(encodeURI('../api/v1/attachment/showVideo?filePath=' + filePath));
        }

        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id="menu.journal.editJournal"/>}>
                    <Card>
                        <Form onSubmit={this.submit} style={{maxWidth: 900, margin: "0 auto"}} labelCol={{span: 8}} wrapperCol={{span: 16}}>
                            {getFieldDecorator('id', {initialValue: editData.id})(<Input hidden={true}/>)}
                            {getFieldDecorator('customerId', {initialValue: editData.customerId})(<Input hidden={true}/>)}
                            <Row>
                                <Col span={12}>
                                    <Form.Item label="广告名称" {...formItemLayout}>
                                        {getFieldDecorator('aname', {
                                            initialValue: editData.aname,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入广告名称！',
                                                },
                                            ],
                                        })(<Input placeholder="请输入广告名称" allowClear={allowClear} readOnly={readOnly} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={12} style={{ float: 'right' }}>
                                    <Form.Item label="行业分类" {...formItemLayout}>
                                        {
                                            getFieldDecorator('industry', {
                                                initialValue: editData.industry,
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请选择行业分类！',
                                                    },
                                                ],
                                            })(
                                                <Select placeholder={"请选择行业分类"} allowClear={true} disabled={readOnly}>
                                                    {gvOptions}
                                                </Select>
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item label="所属客户" {...formItemLayout}>
                                        {
                                            getFieldDecorator('customerName', {
                                                initialValue: editData.customerName,
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请选择所属客户！',
                                                    },
                                                ],
                                            })(
                                                <Input placeholder={"请选择所属客户"} readOnly={true} style={{cursor: "pointer"}} onClick={() => {
                                                    if (!readOnly) {
                                                        const { customerList } = this.state;
                                                        if(!customerList) this.findCustomerList();
                                                        else this.setState({isShowCustomerModal: true});
                                                    }
                                                }} />
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                                <Col span={12} style={{ float: 'right' }}>
                                    <Form.Item label="是否赠送" {...formItemLayout}>
                                        {
                                            getFieldDecorator('giveFlag', {
                                                initialValue: APP.changeIsNilVal(editData.giveFlag, 2),
                                                rules: [
                                                    {
                                                        required: false,
                                                        message: '请选择是否赠送！',
                                                    },
                                                ],
                                            })(
                                                <Radio.Group disabled={readOnly}>
                                                    <Radio value={2}>赠送广告</Radio>
                                                    <Radio value={1}>非赠送</Radio>
                                                </Radio.Group>
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item label="广告类型" {...formItemLayout}>
                                        {
                                            getFieldDecorator('atype', {
                                                initialValue: APP.changeIsNilVal(editData.atype, 1),
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请选择广告类型！',
                                                    },
                                                ],
                                            })(
                                                <Select placeholder={"请选择广告类型"} allowClear={true} disabled={readOnly} onChange={item => {
                                                    form.setFieldsValue({"filePath": null});
                                                    that.setState({selectedFile: null, editData: {...editData, filePath: null}});
                                                }}>
                                                    <Select.Option value={1}>视频</Select.Option>
                                                    <Select.Option value={2}>图片</Select.Option>
                                                    <Select.Option value={3}>文字</Select.Option>
                                                    {/*<Select.Option value={4}>其他</Select.Option>*/}
                                                </Select>
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                                {/*<Col span={12} style={{ float: 'right' }}>
                                    <Form.Item label="广告时长" {...formItemLayout}>
                                        {
                                            getFieldDecorator('seconds', {
                                                initialValue: editData.seconds,
                                                rules: [
                                                    {
                                                        required: false,
                                                        message: '请输入广告时长！',
                                                    },
                                                ],
                                            })(
                                                <Input placeholder={"请输入广告时长"} addonAfter="秒" allowClear={allowClear} readOnly={readOnly} />
                                            )
                                        }
                                    </Form.Item>
                                </Col>*/}
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item label="广告过期日期" {...formItemLayout}>
                                        {
                                            getFieldDecorator('expireDate', {
                                                initialValue: (function(){
                                                    const { expireDate } = editData;
                                                    if(expireDate){
                                                        return moment(expireDate, 'YYYY-MM-DD');
                                                    }
                                                })(),
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请选择广告过期日期！',
                                                    },
                                                ],
                                            })(
                                                <DatePicker
                                                    placeholder="请选择广告过期日期"
                                                    style={{
                                                        width: "100%"
                                                    }}
                                                    disabledDate={disabledDate}
                                                    disabled={readOnly}
                                                />
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                                <Col span={12} style={{ float: 'right' }}>
                                    <Form.Item label="广告合同号" {...formItemLayout}>
                                        {
                                            getFieldDecorator('contractNo', {
                                                initialValue: editData.contractNo,
                                                rules: [
                                                    {
                                                        // required: true,
                                                        message: '请输入广告合同号！',
                                                    },
                                                ],
                                            })(
                                                <Input placeholder={"请输入广告合同号"} allowClear={allowClear} readOnly={readOnly} />
                                            )
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={24}>
                                    <Form.Item label={isFile ? "文件素材" : "文本素材"} style={readOnly && (isVideo || isImage) ? {display:'none'} : formItemLayout.style} labelCol={{span: 4}} wrapperCol={{span: 20}}>
                                        {
                                            getFieldDecorator('filePath', {
                                                initialValue: editData.filePath,
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请上传素材！',
                                                    },
                                                ],
                                            })(
                                                isFile ? (
                                                    <Dragger {...uploadHandler}>
                                                        <p className="ant-upload-drag-icon">
                                                            <Icon type="inbox" />
                                                        </p>
                                                        <p className="ant-upload-text">点击或将文件拖拽到此区域上传</p>
                                                        <p className="ant-upload-hint" style={{color:'red',fontWeight:'bold'}}>注：每个期刊只能上传一个MP4格式视频或图片，最低分辨率要求为1280*720</p>
                                                    </Dragger>
                                                ) : (
                                                    <Input.TextArea placeholder={"请输入文本素材，不能超过300字符"} allowClear={allowClear} readOnly={readOnly} />
                                                )
                                            )
                                        }
                                    </Form.Item>
                                    {
                                        (isVideo || isImage) && (APP.isValidObj(selectedFile) || APP.isValidObj(editData.filePath)) ? (
                                            <Form.Item label="素材预览" {...formItemLayout} labelCol={{span: 4}} wrapperCol={{span: 20}}>
                                                {
                                                    isVideo ? (
                                                        <video
                                                            src={APP.isValidObj(selectedFile) ? (selectedFile.isServerPath ? selectedFile.filePath : getLocalFile(selectedFile.filePath)) : editData.filePath}
                                                            controls="controls"
                                                            style={{ width: 350, height: 200 }}
                                                        />
                                                    ) : (
                                                        <div
                                                            style={{
                                                                width: 350,
                                                                height: 200,
                                                                backgroundImage: `url("${APP.isValidObj(selectedFile) ? selectedFile.filePath : editData.filePath}")`,
                                                                backgroundRepeat: 'no-repeat',
                                                                backgroundPosition: 'center',
                                                                backgroundSize: 'cover',
                                                                border: '1px solid #d9d9d9',
                                                                borderRadius: 6
                                                            }}
                                                        />
                                                    )
                                                }
                                            </Form.Item>
                                        ) : <div/>
                                    }
                                </Col>
                            </Row>
                            <Row>
                                <Col span={24}>
                                    <Form.Item label="备注" {...formItemLayout} labelCol={{span: 4}} wrapperCol={{span: 20}}>
                                        {
                                            getFieldDecorator('remark', {
                                                initialValue: editData.remark,
                                            })(<Input.TextArea
                                                placeholder="请输入备注"
                                                className="custom"
                                                style={{ height: 150,resize:'none' }}
                                                allowClear={allowClear}
                                                readOnly={readOnly}
                                            />)
                                        }
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{ textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20 }}>
                                    {submitBtn}
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                        this.setState({selectedFile: null});
                                        form.resetFields();
                                    }} hidden={readOnly}>
                                        重置
                                    </Button>
                                    {callbackToListBtn}
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <AddPointView parent={this} />
                    <CustomerModal parent={this} />
                    <ProgressSpin parent={this} />
                </PageHeaderWrapper>
            </Spin>
        );
    }

    getJournalMaxLimit() {
        const that = this;
        const { dispatch } = that.props;
        dispatch({
            type: "journalModel/getJournalMaxLimit",
            payload: {},
            callback: function(data){
                if(data.success){
                    that.setState({journalMaxLimit: data.datas});
                }
            }
        });
    }
}

/**
 * 客户选择窗口
 * @Author 肖家添
 * @Date 2020/3/18 23:18
 */
const CustomerModal = Form.create()((props => {
    const { parent, form } = props;
    const { loading, isShowCustomerModal, editData, customerList } = parent.state;
    const { getFieldDecorator } = form;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };
    //-- 提交
    function submit(e){
        parent.findCustomerList(e, form);
    }
    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal(){
        form.resetFields();
        let { isShowCustomerModal } = parent.state;
        isShowCustomerModal = !isShowCustomerModal;
        parent.setState({ isShowCustomerModal });
    }
    if(!customerList) return <div></div>;
    return (
        <Modal
            visible={isShowCustomerModal}
            width={800}
            confirmLoading={loading}
            footer={false}
            onCancel={() => handlerEditModal()}
        >
            <Spin spinning={loading}>
                <Form onSubmit={submit} layout={"inline"} style={{marginBottom: 20}}>
                    <Form.Item label="客户名称" {...formItemLayout} {...APP.buttonsStyle_MR15}>
                        {getFieldDecorator('oname', {
                            rules: [{ required: false, message: '请输入客户名称！' }],
                            initialValue: editData.oname
                        })(<Input placeholder="请输入客户名称"/>)}
                    </Form.Item>
                    <Form.Item>
                        <Button type={"primary"} htmlType="submit" {...APP.buttonsStyle_MR15}>查询</Button>
                    </Form.Item>
                </Form>
                <Table
                    bordered
                    rowKey={data => `${data.id}`}
                    columns={[
                        {title: '客户名称', dataIndex: 'oname', key: 'oname'},
                        {title: '所在省市', dataIndex: 'areaName', key: 'areaName'},
                        {title: '详细地址', dataIndex: 'address', key: 'address'},
                        {title: '销售员', dataIndex: 'saleName', key: 'saleName'},
                    ]}
                    dataSource={customerList}
                    onRow={(record) => {
                        return {
                            onClick: event => {
                                const { form } = parent.props;
                                form.setFieldsValue({
                                    customerId: record.id,
                                    customerName: record.oname
                                });
                                handlerEditModal();
                            },
                        };
                    }}
                    pagination={{
                        showTotal: total => `共 ${total} 条数据`,
                    }}
                />
            </Spin>
        </Modal>
    );
}));

/**
 * 添加点位视图
 * @Author 肖家添
 * @Date 2020/3/19 20:52
 */
const AddPointView = Form.create()((props => {
    const { parent, form } = props;
    const { dispatch } = parent.props;
    let { isShowPointModal, loading, pointList, pointSelectedKeys, joPointList, fromList, isShowAddPointModal, editData } = parent.state;
    const journalId = parent.state.editDataId;
    const { getFieldDecorator } = form;
    if(!journalId) {//新增
        return <div></div>;
    }
    //-- 提交
    function submit(){
        if(pointSelectedKeys.length <= 0){
            message.error("请选择需要添加的点位！");
            return;
        }
        APP.loading(parent);
        dispatch({
            type: "journalModel/bindJournalToPoint",
            payload: {
                journalId,
                pointIds: pointSelectedKeys.toLocaleString()
            },
            callback: function(data){
                APP.closeLoading(parent);
                if(data.success){
                    handlerEditModal();
                    parent.findJoPoint(true);
                } else {
                    Modal.error({
                       content:data.msg
                    });
                }
            }
        });
    }
    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal(){
        form.resetFields();
        isShowPointModal = !isShowPointModal;
        parent.setState({ isShowPointModal });
    }
    function findPointList(e) {
        let params = {notLimit: true};
        if(e) e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            params.isenabled = 1;
            requestContinue();
        });
        function requestContinue(){
            APP.loading(parent);
            dispatch({
                type: "pointModel/list",
                payload: params,
                callback: function(data){
                    APP.closeLoading(parent);
                    if(data.success){
                        parent.setState({
                            pointList: data.datas.list,
                            isShowPointModal: true
                        });
                    }
                }
            });
        }
    }
    function removeJoPoint(id){
        APP.loading(parent);
        dispatch({
            type: "journalModel/removeJoPoint",
            payload: {id},
            callback: function(data){
                APP.closeLoading(parent);
                if(data.success){
                    parent.findJoPoint(true);
                }
            }
        });
    }
    let readOnly = false;
    if (fromList === 'look') {
        readOnly = true;
    }
    const columns = [
        {title: '运营商', dataIndex: 'operatorName', key: 'operatorName'},
        {title: '楼盘名称', dataIndex: 'hourseName', key: 'hourseName'},
        {title: '区域', dataIndex: 'areaName', key: 'areaName'},
        {title: '点位名称', dataIndex: 'elevatorName', key: 'elevatorName'},
        {title: '设备类型', dataIndex: 'pTypeName', key: 'pTypeName'},
        {title: '设备生产商', dataIndex: 'producer', key: 'producer'},
        {title: '联网类型', dataIndex: 'networkTypeName', key: 'networkTypeName'},
        {title: '机器串码', dataIndex: 'imei', key: 'imei'},
        {title: '点位状态', dataIndex: 'pointIsenabled', key: 'pointIsenabled',
            render: (text) => {
                if(text.indexOf('删除') > -1) {
                    text = <span style={{color:'red'}}>{text}</span>;
                }
                return text;
            }},
        {title: '设备状态', dataIndex: 'xstatus', key: 'xstatus'},
        {title: '该期刊上传状态', dataIndex: 'sourceXstatus', key: 'sourceXstatus'},
        {title: '点位已有期刊数量', dataIndex: 'journalCount', key: 'journalCount'},
    ];
    if (!readOnly) {
        columns.push({title: '操作', render: (text, record) => {
            return (
                <Popconfirm
                    title="确定删除选中数据吗？"
                    onConfirm={() => removeJoPoint(record.id)}
                    okText="删除"
                    cancelText="取消"
                >
                    <a>删除</a>
                </Popconfirm>
            );
        }});
    }
    let html =
            <Card style={{marginTop: 15}}>
                <div style={{marginBottom: 20}}>
                    <span style={{fontWeight: "bold", fontSize: 20, marginRight: 30}}>已选点位</span>
                    <a onClick={() => {
                        if(!pointList) findPointList();
                        else parent.setState({isShowPointModal: true});
                    }} hidden={readOnly}>添加点位</a>
                </div>
                <Table
                    bordered
                    rowKey={data => `${data.id}`}
                    columns={columns}
                    dataSource={joPointList}
                    pagination={{
                        showTotal: total => `共 ${total} 条数据`,
                    }}
                />
                <Modal
                    visible={isShowPointModal}
                    width={1000}
                    confirmLoading={loading}
                    footer={false}
                    onCancel={() => handlerEditModal()}
                >
                    <Spin spinning={loading}>
                        <Form onSubmit={findPointList} layout={"inline"} style={{marginBottom: 20}}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="楼盘名称">
                                        {getFieldDecorator('houseName', {})(<Input placeholder="请输入楼盘名称"/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="点位名称">
                                        {getFieldDecorator('elevatorName', {})(<Input placeholder="请输入点位名称"/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="机器串码">
                                        {getFieldDecorator('imei', {})(<Input placeholder="请输入机器串码"/>)}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{textAlign: 'center', height: '32px', lineHeight: '32px'}}>
                                    <Form.Item>
                                        <Button type={"primary"} htmlType="submit" {...APP.buttonsStyle_MR15}>查询</Button>
                                        <Button type={"primary"} {...APP.buttonsStyle_MR15} onClick={submit}>添加</Button>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            columns={[
                                {title: '运营商', dataIndex: 'operatorName', key: 'operatorName'},
                                {title: '楼盘名称', dataIndex: 'hourseName', key: 'hourseName'},
                                {title: '区域', dataIndex: 'areaName', key: 'areaName'},
                                {title: '点位名称', dataIndex: 'elevatorName', key: 'elevatorName'},
                                {title: '设备类型', dataIndex: 'pTypeName', key: 'pTypeName'},
                                {title: '设备生产商', dataIndex: 'producer', key: 'producer'},
                                {title: '联网类型', dataIndex: 'networkTypeName', key: 'networkTypeName'},
                                {title: '机器串码', dataIndex: 'imei', key: 'imei'},
                                {title: '状态', dataIndex: 'xstatus', key: 'xstatus'},
                                {title: '期刊数量', dataIndex: 'journalCount', key: 'journalCount'},
                            ]}
                            dataSource={pointList}
                            rowSelection={APP.tableRowSelection(function(selectedRowKeys, selectedRows){
                                parent.setState({ pointSelectedKeys: selectedRowKeys });
                            }, pointSelectedKeys)}
                            onRow={record => {
                                return {
                                    onClick: event => {
                                        event.currentTarget.getElementsByClassName("ant-checkbox-wrapper")[0].click();
                                    }
                                };
                            }}
                            pagination={{
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Spin>
                </Modal>
            </Card>;
    if (fromList !== 'edit' && fromList !== 'look') {//编辑按钮
        html = <Modal
            visible={isShowAddPointModal}
            width={1200}
            footer={false}
            onCancel={() => {
              router.push({pathname: '/journal/journal'});
            }}
        >{html}</Modal>;
    }
    return (html);
}));

const ProgressSpin = Form.create()((props => {
    const { parent } = props;
    const { progressShow, percent } = parent.state;
    let display = progressShow ? 'block' : 'none';
    return (
        <div style={{
            display: display,
        }}>
            <div style={{
                position: 'fixed',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: 'black',
                opacity: 0.6,
                zIndex:1000
            }}>
            </div>
            <Progress
                type={"circle"}
                percent={percent}
                format={percent => <span style={{color:'red'}}>{percent}%</span>}
                style={{
                    position: 'fixed',
                    top: '25%',
                    left: '50%',
                    zIndex:5000
                }}
            />
        </div>
    );
}));
export default editJournal;
